package com.atguigu.controller;


import com.atguigu.entity.Admin;
import com.atguigu.entity.HouseBroker;
import com.atguigu.service.AdminService;
import com.atguigu.service.HouseBrokerService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/houseBroker")
public class HouseBrokerController {

    @DubboReference
    private AdminService adminService;

    @DubboReference
    private HouseBrokerService houseBrokerService;

    //   渲染create的视图处理去 查询所有的admin放入请求域
    @RequestMapping("/create")
    public String create(Long houseId, ModelMap modelMap) {
//        查询所有的admin
        List<Admin> adminList = adminService.findAll();
        modelMap.addAttribute("houseId", houseId);
        modelMap.addAttribute("adminList", adminList);
        return "houseBroker/create";
    }

    @RequestMapping("/save")
    public String save(HouseBroker houseBroker) {
//        根据id查询admin
        Admin admin = adminService.getById(houseBroker.getBrokerId());
        houseBroker.setBrokerId(admin.getId());
        houseBroker.setBrokerHeadUrl(admin.getHeadUrl());
        houseBroker.setBrokerName(admin.getName());
        houseBrokerService.insert(houseBroker);
        return "common/successPage";
    }

    @GetMapping("/edit/{id}")
    public String edit(ModelMap model,@PathVariable("id") Long id) {
        HouseBroker houseBroker = houseBrokerService.getById(id);
        List<Admin> adminList = adminService.findAll();
        model.addAttribute("adminList",adminList);
        model.addAttribute("houseBroker",houseBroker);
        return "houseBroker/edit";
    }
    @PostMapping("/update")
    public String update(HouseBroker houseBroker) {
        Admin admin = adminService.getById(houseBroker.getBrokerId());
        houseBroker.setBrokerName(admin.getName());
        houseBroker.setBrokerHeadUrl(admin.getHeadUrl());
        houseBrokerService.update(houseBroker);
        return "common/successPage";
    }
    /**
     * 删除
     * @param id
     * @return
     */
    @GetMapping("/delete/{houseId}/{id}")
    public String delete(@PathVariable Long houseId, @PathVariable Long id) {
        houseBrokerService.delete(id);
        return "redirect:/house/" + houseId;
    }
}
